package com.whfc.cncit.helmet.client;

import com.whfc.cncit.helmet.codec.CncitMsgDecoder;
import com.whfc.cncit.helmet.codec.CncitMsgEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

import static com.whfc.cncit.constant.CncitConst.FRAME_DELIMITER;

public class HelmetClient {

    public void connect(String host, int port) throws Exception {

        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.AUTO_READ, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, false, Unpooled.copiedBuffer(new byte[]{FRAME_DELIMITER})));
                    ch.pipeline().addLast(new IdleStateHandler(6, 0, 0, TimeUnit.MINUTES));
                    ch.pipeline().addLast(new CncitMsgDecoder());
                    ch.pipeline().addLast(new CncitMsgEncoder());
                    ch.pipeline().addLast(new HelmetClientHandler());
                }
            });
            ChannelFuture f = b.connect(host, port).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        String host = "";
        host = "123.60.53.116";//测试
//        host = "121.196.130.108";//生产
//        host = "localhost";
        HelmetClient client = new HelmetClient();
        client.connect(host, 8130);
    }
}
